<template>
  <slot :wechatLogin="onTriggerClick"/>
  <el-dialog v-model="visible" width="300px" title="微信扫码登录" :close-on-click-modal="true">
    <div style="text-align: center">
      <img
          :src="qrCodeUrl"
          width="235" height="250" alt=""
      />
      <p style="margin-top: 12px">请使用微信扫码登录</p>
    </div>
  </el-dialog>
</template>

<script setup>
import {ref, onBeforeUnmount} from 'vue'
import {useRouter} from 'vue-router'
import {localSave} from '@/utils/local-util.ts'
import {getNewToken, getQrCodeSync, subscribe1} from '@/api/WeChat/index.ts'

const visible = ref(false)
const qrCodeUrl = ref('')
let ticket = ''
let pollingTimeout = null
let isLoggedIn = false
const router = useRouter()
// 触发入口
const onTriggerClick = async () => {
  visible.value = true
  isLoggedIn = false
  await initData()
  await getQrCode()
  await loopGet()
}
// 初始化微信接口 token
const initData = async () => {
  await getNewToken()
}
// 获取二维码
const getQrCode = async () => {
  const myId = Math.floor(Math.random() * 1000000) || 555
  sessionStorage.setItem('myId', myId.toString())
  const res = await getQrCodeSync({
    expire_seconds: 604800,
    action_name: 'QR_SCENE',
    action_info: {scene: {scene_id: myId}},
  })
  ticket = res.ticket
  qrCodeUrl.value = `https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=${res.ticket}`
}
// 轮询是否扫码
const loopGet = async () => {
  if (isLoggedIn) return
  try {
    const rel = await subscribe1({
      ticket,
      myId: sessionStorage.getItem('myId'),
    })
    if (rel && rel.data) {
      isLoggedIn = true
      clearTimeout(pollingTimeout)
      visible.value = false
      message.success('登录成功')
      localSave("smart_admin_user_token", rel.token || '')
      await router.push('/home')
    } else {
      pollingTimeout = setTimeout(loopGet, 5000)
    }
  } catch (err) {
    console.error('轮询出错:', err)
    pollingTimeout = setTimeout(loopGet, 5000)
  }
}
onBeforeUnmount(() => {
  if (pollingTimeout) {
    clearTimeout(pollingTimeout)
  }
})
</script>
